import JSEncrypt from 'jsencrypt';

// 加密
export function encrypt(password) {
    const instance = new JSEncrypt(),
        publickKey = `MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCC/FAJSsiEufRGbMCXtsGWWcWvYYJbtAWbd9juNEdiPczDWe/HLcUKOr4lHtl3ZnkZQYaiGJmSdmIj3FFB2cSADnqes05hJz2YfAzCc/7qYYEyHC2jIuzH75ya/OQH3Cc8IwCUDTbiTGAxUVFVAshFqcXSQYSHE29df+/oX9LLTQIDAQAB`;

    instance.setPublicKey(publickKey);
    return instance.encrypt(password);
}

// 获取本地存储数据项
export function getLocalStorageItem(k) {
    let v = localStorage[k];
    try {
        return v ? JSON.parse(v) : {};
    } catch (error) {
        return v;
    }
}

// 设置本地存储数据项，不传值等于移除数据项
export function setLocalStorageItem(k, v) {
    if (!v) {
        delete localStorage[k];
        return;
    }

    localStorage[k] = JSON.stringify(v);
}


// 重命名对象键名
export function renameObjectKeys(target, keyMapping) {

    if (typeof target !== 'object' || typeof keyMapping !== 'object') return target;

    if (Array.isArray(target) && target.length) {
        return target.map(function (item) {
            return renameObjectKeys(item, keyMapping);
        })
    }

    for (let key in target) {
        let mappedKey = keyMapping[key];

        if (mappedKey && mappedKey !== key) {
            target[mappedKey] = target[key];
            delete target[key];
            key = mappedKey;
        }

        if ('children' === key || 'childs' === key) {
            target[key] = renameObjectKeys(target[key], keyMapping);
        }
    }

    return target;
}

export function extendObject(object, source) {
    for (const key in object) {
        if (key in source) {
            object[key] = source[key];
        }
    }

    return object;
}

export function formatTimeStamp(timeStamp) {
    if (timeStamp === null) return NaN;
    let dateObj = new Date(timeStamp),
        year = dateObj.getFullYear(),
        month = dateObj.getMonth() + 1,
        date = dateObj.getDate(),
        h = dateObj.getHours(),
        m = dateObj.getMinutes(),
        s = dateObj.getSeconds();

    month = month < 10 ? '0' + month : month;
    date = date < 10 ? '0' + date : date;
    h = h < 10 ? '0' + h : h;
    m = m < 10 ? '0' + m : m;
    s = s < 10 ? '0' + s : s;

    return `${year}-${month}-${date} ${h}:${m}:${s}`;
}


// heic转jpeg
// export function toJpeg(url) {
//     let errorImage = '';
//     // 如果是数组
//     if (Array.isArray(url)) {
//         return Promise.all(
//             url.map(item => {
//                 return item && fetch(item).then(res => res.blob())
//                     .then(blob => heicToAny({ blob, toType: 'image/jpeg' }))
//                     .then(conversionRes => window.URL.createObjectURL(conversionRes))
//                     .catch(error => errorImage)
//             })
//         );
//     } else {
//         return url && fetch(url).then(res => res.blob())
//             .then(blob => heicToAny({ blob, toType: 'image/jpeg' }))
//             .then(conversionRes => window.URL.createObjectURL(conversionRes))
//             .catch(error => errorImage)
//     }

//     // fetch(url)
//     //     .then(res => res.blob())
//     //     .then(blob => heicToAny({ blob, toType: 'image/png' }))
//     //     .then(conversionResult => {
//     //         el.src = window.URL.createObjectURL(conversionResult);
//     //         // el.addEventListener('load', function () {
//     //         //     window.URL.revokeObjectURL(this.src);
//     //         // })
//     //     })
//     //     .catch(error => {
//     //         el.src = error.message;
//     //         el.alt = error.message;
//     //     })
// }


/**
 * 格式化金额
 * @param {number} cent 金额/分
 * @returns {string} 格式化过后的金额
 */
export function formatAmount(cent) {
    cent = +cent;
    return isNaN(cent) ? cent : (cent / 100).toFixed(2);
}